# coding:utf-8
from dataclasses import dataclass
import re
import os
import sys
import json
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtWidgets import (
    QWidget,
    QHBoxLayout,
    QVBoxLayout,
    StrongBodyLabel,
    QFrame,
    QFormLayout,
    QLabel,
)
from qfluentwidgets import (
    IconWidget,
    FluentIcon,
)
from qframelesswindow.webengine import FramelessWebEngineView


from .base_gallery_view import GalleryInterface
from .common.translator import Translator
from .base_gallery_view import GalleryInterface
from service.stock_service import getAllStockListSample


@dataclass
class FormItemDto:

    # 表单名称 ：
    form_desc: str

    # 表单主键
    form_key: str

    # 表单值
    form_value: str

    # 表单值类型
    form_value_type: str

    # 表单最大值
    from_max: int

    # 表单最小值
    form_min: int

    # 表单关联表
    form_table: str


class BasePageTemplateView(GalleryInterface):
    """Scroll interface"""

    def __init__(self, objectName, parent=None):
        t = Translator()
        super().__init__(
            title=t.scroll, subtitle="qfluentwidgets.components.widgets", parent=parent
        )
        self.setObjectName(objectName)
        self.searchKey = ""
        self.cardView = []

        self.topView = self.getTopView(self)
        self.vBoxLayout.addWidget(self.topView)

    def getTopView(self):
        return QWidget

    def addCardTemplate(self, itemCard: MainCardTemplate):
        return QWidget


class MainCardTemplate(QWidget):
    """通用卡片对象"""

    def __init__(self, title, widget: QWidget, stretch=0, parent=None):
        super().__init__(parent=parent)
        self.widget = widget
        self.stretch = stretch

        self.titleLabel = StrongBodyLabel(title, self)
        self.card = QFrame(self)

        self.sourceWidget = QFrame(self.card)
        self.linkIcon = IconWidget(FluentIcon.LINK, self.sourceWidget)

        self.vBoxLayout = QVBoxLayout(self)
        self.cardLayout = QVBoxLayout(self.card)
        self.topLayout = QHBoxLayout()
        self.bottomLayout = QHBoxLayout(self.sourceWidget)

        self.__initWidget()

    def __initWidget(self):
        self.linkIcon.setFixedSize(16, 16)
        self.__initLayout()

        self.sourceWidget.setCursor(Qt.CursorShape.PointingHandCursor)
        self.sourceWidget.installEventFilter(self)

        self.card.setObjectName("card")
        self.sourceWidget.setObjectName("sourceWidget")

    def __initLayout(self):
        self.vBoxLayout.setSizeConstraint(QVBoxLayout.SizeConstraint.SetMinimumSize)
        self.cardLayout.setSizeConstraint(QVBoxLayout.SizeConstraint.SetMinimumSize)
        self.topLayout.setSizeConstraint(QHBoxLayout.SizeConstraint.SetMinimumSize)

        self.vBoxLayout.setSpacing(12)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.topLayout.setContentsMargins(12, 12, 12, 12)
        self.bottomLayout.setContentsMargins(18, 18, 18, 18)
        self.cardLayout.setContentsMargins(0, 0, 0, 0)

        self.vBoxLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.addWidget(self.card, 0, Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.cardLayout.setSpacing(0)
        self.cardLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.cardLayout.addLayout(self.topLayout, 0)
        self.cardLayout.addWidget(self.sourceWidget, 0, Qt.AlignmentFlag.AlignBottom)

        self.widget.setParent(self.card)
        self.topLayout.addWidget(self.widget)
        if self.stretch == 0:
            self.topLayout.addStretch(1)

        self.widget.show()

        self.bottomLayout.addStretch(1)
        self.bottomLayout.addWidget(self.linkIcon, 0, Qt.AlignmentFlag.AlignRight)
        self.bottomLayout.setAlignment(
            Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
        )


class MainFormTemplate(QWidget):
    def __init__(self, form_items: List[FormItemDto]):
        super().__init__()
        self.form_items = form_items
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Dynamic Form")
        layout = QVBoxLayout()
        form_layout = QFormLayout()

        self.fields = {}  # Store references to the input widgets

        for item in self.form_items:
            label = QLabel(item.form_desc)

            if item.form_value_type == "text":
                input_field = QLineEdit()
                input_field.setText(item.form_value)
            elif item.form_value_type == "int":
                input_field = QSpinBox()
                if item.form_max is not None:
                    input_field.setMaximum(item.form_max)
                if item.form_min is not None:
                    input_field.setMinimum(item.form_min)
                input_field.setValue(
                    int(item.form_value) if item.form_value.isdigit() else 0
                )
            elif item.form_value_type == "select":
                input_field = QComboBox()
                if item.form_table:
                    options = item.form_table.split(
                        ","
                    )  # Assuming options are comma-separated
                    input_field.addItems(options)
                if item.form_value:
                    input_field.setCurrentText(item.form_value)
            else:
                input_field = QLabel(f"Unsupported field type: {item.form_value_type}")

            form_layout.addRow(label, input_field)
            self.fields[item.form_key] = input_field  # Store reference by form_key

        submit_button = QPushButton("Submit")
        submit_button.clicked.connect(self.submit_form)
        layout.addLayout(form_layout)
        layout.addWidget(submit_button)

        self.setLayout(layout)

    def submit_form(self):
        form_data = {}
        for key, widget in self.fields.items():
            if isinstance(widget, QLineEdit):
                form_data[key] = widget.text()
            elif isinstance(widget, QSpinBox):
                form_data[key] = widget.value()
            elif isinstance(widget, QComboBox):
                form_data[key] = widget.currentText()
            else:
                form_data[key] = None
        print("Form Data:", form_data)
        # You can further process or store form_data
